﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotaHelp.Models;
using DotaHelp.Helpers;
using System.Data.Objects;
using System.Data.Objects.SqlClient;


namespace DotaHelp.Controllers
{
    
    public class StatisticsController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            model.Dispose();
            
        }
       

        public class ListRowGroupVM<T>
        {
            public T Object;
            public int Count;
        }


        public class ListRowVM
        {
            public Func<HtmlHelper, MvcHtmlString> Link;
            public int Count;
            public int Percent;

            public static IEnumerable<ListRowVM> Select<T>(IQueryable<ListRowGroupVM<T>> query, bool isAsc, bool isTop, Func<HtmlHelper, T, MvcHtmlString> DrawLink, bool needSort = true)
            {
                IQueryable<ListRowGroupVM<T>> ordered;

				if (needSort)
				{
					if (isAsc)
					{
						ordered = query.OrderBy(g => g.Count);
					}
					else
					{
						ordered = query.OrderByDescending(g => g.Count);
					}
				}
				else
				{
					ordered = query;
				}

                if (isTop)
                {
                    ordered = ordered.Take(5);
                }

                var max = ordered.Max(g => g.Count);
                if (max == 0) { max = 1; }

                return ordered.ToArray().Select(g => new ListRowVM { Link = h=>DrawLink(h, g.Object) , Count = g.Count, Percent = g.Count * 100 / max });
            }
        };

        
        [Sitemap]
        public ActionResult List(string section=null)
        {
            // Гайды			 
			var guides = model.Heroes.Where(a => a.Id != 1001).Select(h => new ListRowGroupVM<Hero> { Object = h, Count = h.Guides.Where(g => !g.IsDeleted).Count() });
            var pur = model.Heroes.Where(a => a.Id != 1001).Select(h => new ListRowGroupVM<Hero> { Object = h, Count = h.Purchases.Where(g => !g.IsDeleted).Count() });
            var cmd = model.Heroes.Where(a => a.Id != 1001).Select(h => new ListRowGroupVM<Hero> { Object = h, Count = h.CommandsHeroes.Where(ch => !ch.Command.IsDeleted).Count() });
            var items = model.Items.Where(a => a.Id != -1).Select(i => new ListRowGroupVM<Item> { Object = i, Count = i.PurchasesItems.Where(p => !p.Purchase.IsDeleted).Count() });
            var heroes = model.Heroes.Where(a => a.Id != 1001).Select(h => new ListRowGroupVM<Hero> { Object = h, Count = h.Raiting });
            var authorGaids = model.Guides.Where(c => !c.IsDeleted).GroupBy(g => g.Author).Select(group => new ListRowGroupVM<string> { Object = group.Key, Count = group.Count() });
            var authorPur = model.Purchases.Where(c => !c.IsDeleted).GroupBy(g => g.Author).Select(group => new ListRowGroupVM<string> { Object = group.Key, Count = group.Count() });
            var authorCmd = model.Commands.Where(c=>!c.IsDeleted).GroupBy(g => g.Author).Select(group => new ListRowGroupVM<string> { Object = group.Key, Count = group.Count() });
            var authorDic = model.Comments.Where(c => !c.IsDeleted).Where(c=>!c.Author.StartsWith("_admin_")).Where(c=>c.Url.StartsWith("/Word/")).GroupBy(g => g.Author).Select(group => new ListRowGroupVM<string> { Object = group.Key, Count = group.Count() });

			var dayOfLastWeek = DateTime.Now.AddDays(-14);
			var comments = model.Comments.Where(c => c.PostDate > dayOfLastWeek && c.IsDeleted == false).GroupBy(c => EntityFunctions.TruncateTime(c.PostDate)).OrderBy(c=>c.Key.Value).Select(group => new ListRowGroupVM<DateTime?> { Object = group.Key.Value, Count = group.Count() }); 
            

            Func<HtmlHelper, Hero, MvcHtmlString> drawLinkOnHero = (helper, hero) => helper.LinkOnHero(hero, true);

            var groups = new List<Tuple<string, IEnumerable<ListRowVM>>>();

			if (section == null || section == "Comments")
			{
				groups.Add(
					Tuple.Create("Количество комментариев по дате", ListRowVM.Select(comments, false, false, (helper, date) => MvcHtmlString.Create(date.Value.ToShortDateString()), false)));
			}

            if (section == null)
            {
                groups.Add(
                  Tuple.Create("Герои, для которых редко составляют гайды", ListRowVM.Select(guides, true, section == null, drawLinkOnHero)));
            }
            if (section == null || section == "Guides")
            {
                groups.Add(
                    Tuple.Create("Герои, для которых часто составляют гайды", ListRowVM.Select(guides, false, section == null, drawLinkOnHero)));
            }
			
            if (section == null)
            {
                groups.Add(
                    Tuple.Create("Герои, для которых редко составляют закупы", ListRowVM.Select(pur, true, section == null, drawLinkOnHero)));
            }
            if (section == null || section == "Purchases")
            {
                groups.Add(
                    Tuple.Create("Герои, для которых часто составляют закупы", ListRowVM.Select(pur, false, section == null, drawLinkOnHero)));
            }
            if (section == null)
            {
                groups.Add(
                    Tuple.Create("Герои, которых редко пикают или банят в команду", ListRowVM.Select(cmd, true, section == null, drawLinkOnHero)));
            }
            if (section == null || section == "Comands")
            {
                groups.Add(
                Tuple.Create("Герои, которых часто пикают или банят в команду", ListRowVM.Select(cmd, false, section == null, drawLinkOnHero)));
            }
            if (section == null)
            {
                groups.Add(
                    Tuple.Create("Предметы, которые редко используют в закупах", ListRowVM.Select(items, true, section == null, (helper, item) => helper.LinkOnItem(item, isSmall: true))));
            }
            if (section == null || section == "Items")
            {
                groups.Add(
                 Tuple.Create("Предметы, которые часто используют в закупах", ListRowVM.Select(items, false, section == null, (helper, item) => helper.LinkOnItem(item, isSmall: true))));
            }
            if (section == null)
            {
                groups.Add(
                    Tuple.Create("Герои с самым низким рейтингом", ListRowVM.Select(heroes, true, section == null, drawLinkOnHero)));
            }
            if (section == null || section == "Heroes")
            {
                groups.Add(
                    Tuple.Create("Герои с самым высоким рейтингом", ListRowVM.Select(heroes, false, section == null, drawLinkOnHero)));
            }
            if (section == null || section == "authorGaids")
           {
                groups.Add(
                   // Tuple.Create("Авторы, которые написали много гайдов", ListRowVM.Select(authorGaids, false, section == null, (helper, author) => helper.LinkOnAuthor(author))));
                Tuple.Create("Авторы, которые написали много гайдов", ListRowVM.Select(authorGaids, false, section == null, (helper, userName) => helper.ShowUserName(userName))));
            }
            if (section == null || section == "authorPur")
            {
                groups.Add(
                    // Tuple.Create("Авторы, которые написали много гайдов", ListRowVM.Select(authorGaids, false, section == null, (helper, author) => helper.LinkOnAuthor(author))));
                Tuple.Create("Авторы, которые сделали много закупов", ListRowVM.Select(authorPur, false, section == null, (helper, userName) => helper.ShowUserName(userName))));
            }
            if (section == null || section == "authorCmd")
            {
                groups.Add(
                    // Tuple.Create("Авторы, которые написали много гайдов", ListRowVM.Select(authorGaids, false, section == null, (helper, author) => helper.LinkOnAuthor(author))));
                Tuple.Create("Авторы, которые собрали много команд", ListRowVM.Select(authorCmd, false, section == null, (helper, userName) => helper.ShowUserName(userName))));
            }
            if (section == null || section == "authorDic")
            {
                groups.Add(
                    // Tuple.Create("Авторы, которые написали много гайдов", ListRowVM.Select(authorGaids, false, section == null, (helper, author) => helper.LinkOnAuthor(author))));
                Tuple.Create("Авторы, которые добавили много описаний слов в словаре", ListRowVM.Select(authorDic, false, section == null, (helper, userName) => helper.ShowUserName(userName))));
            }
            

            return View(groups);
        }

    }
}
